import os
import json


def is_header_file(file):
    """判断是否为头文件"""
    return file.endswith(".h")


def is_source_file(file):
    """判断是否为源文件"""
    return file.endswith(".c")


def contains_include(path):
    """判断路径中是否包含 "include" """
    return "include" in path


def canonical_path(root, path, use_relative_path=True):
    """将路径转为相对于 root 的路径"""
    path = path.replace("\\", "/")
    root = root.replace("\\", "/")
    if use_relative_path:
        try:
            # relpath 在 Windows 上跨驱动器时会失败
            return os.path.relpath(path, root).replace("\\", "/")
        except ValueError:
            return path  # 失败时回退到绝对路径
    else:
        return path


def write_file_json(path, content):
    """写 JSON 文件"""
    with open(path, "w", encoding="utf-8") as f:
        json.dump(content, f, indent=4, ensure_ascii=False)
